/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador;

import dao.ProgramaJpaController;
import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import logica.Programa;

/**
 *
 * @author andrescsr
 */
public class ProgramaController {
    private EntityManagerFactory factory;
    private ConnectionFactory connection;
    private ProgramaJpaController daoPrograma;

    public ProgramaController() {
        ConnectionFactory connection = new ConnectionFactory();
        factory= connection.getFactory();
        daoPrograma = new ProgramaJpaController(factory);
    }
    
    public int guardar(String codigo, String nombre, String nivel, int numCreditos){
        Programa p = new Programa();
        p.setCodigo(codigo);
        p.setNombre(nombre);
        p.setNivel(nivel);
        p.setNumCreditos(numCreditos);
        try {
            daoPrograma.create(p);
            return -1;
        } catch (PreexistingEntityException ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }
    
    public int borrar(String codigo){
        try {
            daoPrograma.destroy(codigo);
            return -1;
        } catch (IllegalOrphanException ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }
    
    public void modificar(String codigo, String nombre, String nivel, int numCreditos){
        Programa p = daoPrograma.findPrograma(codigo);
        p.setCodigo(codigo);
        p.setNombre(nombre);
        p.setNivel(nivel);
        p.setNumCreditos(numCreditos);
        
        try {
            daoPrograma.edit(p);
        } catch (IllegalOrphanException ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ProgramaController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public Programa consultar(String codigo){
        Programa p = null;
        p = daoPrograma.findPrograma(codigo);
        return p;
    }
    
    public List<Programa> consultarTodo(){
        List<Programa> programas = daoPrograma.findProgramaEntities();
        return programas;
    }
}